<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-left">
      <div class="JG-common-tree-search">
        <el-input
          placeholder="输入分类搜索"
          v-model="filterText">
        </el-input>
      </div>
      <el-tree :data="treeData" :props="treeProps" default-expand-all highlight-current ref="treeBox" :filter-node-method="filterNode"
        :expand-on-click-node="false" @node-click="handleNodeClick" class="JNPF-common-el-tree" node-key="id">
      </el-tree>
    </div>
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item>
              <el-input v-model="query.title" placeholder="输入标题" clearable> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="query.supplydemandtype"  placeholder="供需类型" clearable :style='{"width":"100%"}' filterable>
                <el-option v-for="(item, index) in supplydemandtypeOptions" :key="index" :label="item.fullName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="query.endmark"  placeholder="是否结束" clearable :style='{"width":"100%"}' filterable>
                <el-option v-for="(item, index) in stateOptions" :key="index" :label="item.fullName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset(true)">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div>
            <!-- <el-button type="primary" @click="addOrUpdateHandle(undefined, undefined, 1)">新增需求</el-button> -->
            <!-- <el-button type="primary" @click="addOrUpdateHandle(undefined, undefined, 0)">新增供应</el-button> -->
            <!-- <el-button type="danger" plain @click="handleBatchRemoveDel()">批量删除</el-button> -->
            <el-button v-has="'btn_batchDownload'" plain @click="download()">批量导出</el-button>
          </div>
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="reset(true)" />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table v-loading="listLoading" :data="list" @sort-change='sortChange' :span-method="arraySpanMethod" :customColumn="true">
          <el-table-column prop="title" label="标题" align="left" show-overflow-tooltip />
          <el-table-column prop="picture" label="图片" align="left">
            <template slot-scope="scope">
              <el-image v-if="scope.row.url" :src="define.comUrl+scope.row.url" class="el-upload-list__item-thumbnail"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="供需分类" prop="typeid" algin="left">
            <template slot-scope="scope">
              {{ scope.row.typeid | dynamicText(typeidOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="supplydemandtype" label="供需类型" align="left">
            <template slot-scope="scope">
              <span>{{scope.row.supplydemandtype == 0 ? '供应' :' 需求'}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="flowState" label="状态" align="left">
            <template slot-scope="scope">
              <div v-if="scope.row.flowState == 1"><span class="JG-common-dot" style="background: #52C1F5;"></span>待审核</div>
              <div v-if="scope.row.flowState == 2 && scope.row.endmark == 0"><span class="JG-common-dot" style="background: #95F204;"></span>进行中</div>
              <div v-if="scope.row.flowState == 2 && scope.row.endmark == 1"><span class="JG-common-dot" style="background: #FFFF00;"></span>已结束</div>
              <div v-if="scope.row.flowState == 3"><span class="JG-common-dot" style="background: #D9001B;"></span>已驳回</div>
            </template>
          </el-table-column> -->
          <el-table-column prop="endmark" label="是否结束" align="left">
            <template slot-scope="scope">
              <div v-if="scope.row.endmark == 0"><span class="JG-common-dot" style="background: #95F204;"></span>进行中</div>
              <div v-if="scope.row.endmark == 1"><span class="JG-common-dot" style="background: #FFFF00;"></span>已结束</div>
            </template>
          </el-table-column>
          <el-table-column prop="flowState" label="审核状态" width="100" align="left">
              <template slot-scope="scope">
                  <el-tag v-if="scope.row.flowState==1">待审核</el-tag>
                  <el-tag type="success" v-if="scope.row.flowState==2">已审核</el-tag>
                  <el-tag type="danger" v-if="scope.row.flowState==3">已驳回</el-tag>
                  <!-- <el-tag type="info" v-else-if="scope.row.flowState==4">流程撤回</el-tag> -->
                  <!-- <el-tag type="info" v-else-if="scope.row.flowState==5">审核终止</el-tag> -->
                  <!-- <el-tag type="warning" v-else>等待提交</el-tag> -->
              </template>
          </el-table-column>
          <el-table-column prop="creatortime" label="创建时间" min-width="140" align="left" />
          <el-table-column label="操作" fixed="right" min-width="100">
            <template slot-scope="scope">
              <el-button v-has="'btn_detail'" type="text" @click="addOrUpdateHandle(scope.row.id,scope.row.flowState)">查看</el-button>
              <!-- <el-button type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除</el-button> -->
              <!-- <el-button type="text" @click="addOrUpdateHandle(scope.row.id)" v-if="scope.row.flowState == 1 || scope.row.flowState == 3">编辑</el-button> -->
              <!-- <el-button type="text" @click="goClose(scope.row.id)" v-if="scope.row.endmark == 0 && scope.row.flowState == 2">关闭</el-button> -->
            </template>
          </el-table-column>
        </JNPF-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <JNPF-Form v-if="formVisible" ref="JNPFForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <Detail v-if="detailVisible" ref="Detail" @refresh="detailVisible=false" />
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />
  </div>
</template>

<script>
  import { getAssoSupplyTypeList } from '@/api/asso/supply/category'
  import { getAssoSupplyInfoList, delAssoSupplyInfo, approveAssoSupplyInfo, unapproveAssoSupplyInfo, closeAssoSupplyInfo, exportAssoSupplyInfo, batchRemoveAssoSupplyInfo } from '@/api/asso/supply/list'
  import JNPFForm from './Form'
  import ExportBox from './ExportBox'
  import Detail from './Detail'
  import FlowBox from '@/views/workFlow/components/FlowBox'
  import columnList from './columnList'

  export default {
    name: 'vipsupplylistindex',
    components: {
      FlowBox,
      JNPFForm,
      ExportBox,
      Detail
    },
    data() {
      return {
        flowVisible: false,
        expandObj: {},
        columnOptions: [],
        mergeList: [],
        exportList: [],
        columnList,
        detailVisible: false,
        query: {
          title: undefined,
        },
        treeProps: {
          children: 'children',
          label: 'fullName',
          value: 'id'
        },
        list: [],
        listLoading: true,
        multipleSelection: [],
        total: 0,
        listQuery: {
          superQueryJson: '',
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "",
        },
        formVisible: false,
        exportBoxVisible: false,
        treeData: [],
        treeActiveId: '',
        typeidOptions: [],
        supplydemandtypeOptions: [{
          fullName: '供应',
          id: 0
        },{
          fullName: '需求',
          id: 1
        }],
        stateOptions: [
        //   {
        //   fullName: '待审核',
        //   id: 1
        // },
        {
          fullName: '进行中',
          id: 0
        },{
          fullName: '已结束',
          id: 1
        }
        // ,{
        //   fullName: '已驳回',
        //   id: 3
        // },
        ],
        filterText: ''
      }
    },
    created() {
        this.getColumnList()
        this.getTreeView()
        this.initData()
    },
    watch: {
      filterText(val) {
        this.$refs.treeBox.filter(val);
      }
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.fullName.indexOf(value) !== -1;
      },
      getColumnList() {
        // 没有开启权限
        this.columnOptions = this.transformColumnList(this.columnList)
      },
      transformColumnList(columnList) {
        let list = []
        for (let i = 0; i < columnList.length; i++) {
          const e = columnList[i];
          if (!e.prop.includes('-')) {
            list.push(e)
          } else {
            let prop = e.prop.split('-')[0]
            let label = e.label.split('-')[0]
            let vModel = e.prop.split('-')[1]
            let newItem = {
              align: "center",
              jnpfKey: "table",
              prop,
              label,
              children: []
            }
            e.vModel = vModel
            if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
            if (!list.some(o => o.prop === prop)) list.push(newItem)
            for (let i = 0; i < list.length; i++) {
              if (list[i].prop === prop) {
                list[i].children.push(e)
                break
              }
            }
          }
        }
        this.getMergeList(list)
        this.getExportList(list)
        return list
      },
      arraySpanMethod({
        column
      }) {
        for (let i = 0; i < this.mergeList.length; i++) {
          if (column.property == this.mergeList[i].prop) {
            return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
          }
        }
      },
      getMergeList(list) {
        let newList = JSON.parse(JSON.stringify(list))
        newList.forEach(item => {
          if (item.children && item.children.length) {
            let child = {
              prop: item.prop + '-child-first'
            }
            item.children.unshift(child)
          }
        })
        newList.forEach(item => {
          if (item.children && item.children.length) {
            item.children.forEach((child, index) => {
              if (index == 0) {
                this.mergeList.push({
                  prop: child.prop,
                  rowspan: 1,
                  colspan: item.children.length
                })
              } else {
                this.mergeList.push({
                  prop: child.prop,
                  rowspan: 0,
                  colspan: 0
                })
              }
            })
          } else {
            this.mergeList.push({
              prop: item.prop,
              rowspan: 1,
              colspan: 1
            })
          }
        })
      },
      getExportList(list) {
        let exportList = []
        for (let i = 0; i < list.length; i++) {
          if (list[i].jnpfKey === 'table') {
            for (let j = 0; j < list[i].children.length; j++) {
              exportList.push(list[i].children[j])
            }
          } else {
            exportList.push(list[i])
          }
        }
        this.exportList = exportList
      },
      goDetail(id) {
        this.detailVisible = true
        this.$nextTick(() => {
          this.$refs.Detail.init(id)
        })
      },
      sortChange({
        column,
        prop,
        order
      }) {
        this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
        this.listQuery.sidx = !order ? '' : prop
        this.initData()
      },
      getTreeView() {
        let _query = {
          superQueryJson: '',
          sort: "desc",
          sidx: "",
          showmark: '1'
        };
        getAssoSupplyTypeList(_query).then((res) => {
          res.data.list.forEach(item => {
            item.children = []
            item.fullName = item.name
          })
          this.treeData = JSON.parse(JSON.stringify(res.data.list))
          this.typeidOptions = JSON.parse(JSON.stringify(res.data.list))
        })
      },
      getNodePath(node) {
        let fullPath = []
        const loop = (node) => {
          if (node.level) fullPath.unshift(node.data)
          if (node.parent) loop(node.parent)
        }
        loop(node)
        return fullPath
      },
      handleNodeClick(data, node) {
        this.treeActiveId = data.id
        for (let
            key in this.query) {
          this.query[key] = undefined
        }
        this.query.typeid = data.id
        this.listQuery = {
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "",
        }
        this.initData()
      },
      initData() {
        this.listLoading = true;
        // if(this.query.state == 4 || this.query.state == 5){
        //   this.query.endmark = this.query.state == 4 ? 0 : 1
        //   this.query.flowState = 2
        // }else{
        //   this.query.endmark = undefined
        //   this.query.flowState = this.query.state
        // }
        let _query = {
          ...this.listQuery,
          ...this.query,
          keyword: this.keyword,
          dataType: 0
        };
        getAssoSupplyInfoList(_query).then((res) => {
          res.data.list.forEach(item=>{
            if(JSON.parse(item.picture)[0]){
              item.url = JSON.parse(item.picture)[0].url
            }
          })
          this.list = JSON.parse(JSON.stringify(res.data.list))
          this.total = res.data.pagination.total
          this.listLoading = false
        }).catch(()=>{
          this.listLoading = false
        })
      },
      handleDel(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          type: 'warning'
        }).then(() => {
          delAssoSupplyInfo(id).then((res) => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        }).catch(() => {});
      },
      goClose(id){
        this.$confirm('是否确认关闭此条需求?', '提示', {
          type: 'warning'
        }).then(() => {
          closeAssoSupplyInfo(id).then((res) => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        }).catch(() => {});
      },
      handleSelectionChange(val) {
        const res = val.map(item => item.id)
        this.multipleSelection = res
      },
      handleBatchRemoveDel() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: 'error',
            message: '请选择一条数据',
            duration: 1500,
          })
          return
        }
        const ids = this.multipleSelection.join()
        this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
          type: 'warning'
        }).then(() => {
          batchRemoveAssoSupplyInfo(ids).then((res) => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        }).catch(() => {})
      },
      addOrUpdateHandle(id, flowState, supplydemandtype) {
        // this.formVisible = true
        // this.$nextTick(() => {
        //   this.$refs.JNPFForm.init(id, supplydemandtype)
        // })
        let data = {
            id: id || '',
            enCode: 'supplyInfo',
            flowId:'366935375857322373',
            formType: 1,
            opType: flowState ? 0 : '-1',
            status: flowState,
            supplydemandtype: supplydemandtype
        }
        this.flowVisible = true
        this.$nextTick(() => {
            this.$refs.FlowBox.init(data)
        })
      },
      colseFlow(isrRefresh) {
          this.flowVisible = false
          if (isrRefresh) this.reset()
      },
      exportData() {
        this.exportBoxVisible = true
        this.$nextTick(() => {
          this.$refs.ExportBox.init(this.exportList)
        })
      },
      download() {
        let query = {
          currentPage: 1,
          dataType: 1,
          pageSize: 20,
          selectKey: "title,listintroduce,typeid,supplydemandtype,creatortime,expiretime,contactname,contactphonenum,detailaddress",
          sidx: "",
          sort: "desc",
          superQueryJson: ""
        }
        exportAssoSupplyInfo(query).then((res) => {
          if (!res.data.url) return
          this.jnpf.downloadFile(res.data.url)
          this.$refs.ExportBox.visible = false
          this.exportBoxVisible = false
        })
      },
      search(init) {
        this.listQuery.currentPage = 1
        this.listQuery.pageSize = 20
        this.listQuery.sort = "desc"
        this.listQuery.sidx = ""
        if(init){
          this.treeActiveId = ''
          this.getTreeView()
        }
        this.initData()
      },
      refresh(isrRefresh) {
        this.formVisible = false
        if (isrRefresh) this.reset()
      },
      reset(init) {
        for (let key in this.query) {
          this.query[key] = undefined
        }
        this.search(init)
      }
    }
  }
</script>
